<template>
  <div class="container">
    <van-sidebar class="aside" v-model="activeKey">
      <van-sidebar-item title="全部" @click="get_dish_list" />
      <van-sidebar-item title="新品推荐" @click="get_dish_list_type(1)" />
      <van-sidebar-item title="销量霸榜" @click="get_dish_list_type(2)" />
      <van-sidebar-item title="用户好评" @click="get_dish_list_type(3)" />
      <van-sidebar-item v-for="item in cuisine_list" :key="item.id" :title="item.name" @click="get_dish_list(item.id)" />
    </van-sidebar>
    <main>
      <form action="/">
        <van-search v-model="keyword" placeholder="请输入搜索关键词" @search="onSearch" @clear="onClear" />
      </form>

      <van-card v-for="item in dish_list" :tag="item.type == 1 ? '新品推荐' : item.type == 2 ? '销量霸榜' : item.type == 3 ? '用户好评' : ''" :key="item.id" :price="item.price" :desc="item.describe" :title="item.name" :thumb="'http://8.138.102.145/images/' + item.img">
        <template #tags>
          <van-tag plain type="danger" v-for="i in item.itemList" :key="i.id">{{ i.name }}</van-tag>
        </template>
        <template #footer>
          <div @click="add_cart(item)">
            <v-icon name="io-add-circle-sharp" fill="#e84b3c"></v-icon>
          </div>
        </template>
      </van-card>
      <van-empty v-if="!dish_list.length" image="search" description="该菜系下没有菜品" />
    </main>
    <van-sku ref="sku" v-model="show" :sku="sku" :goods="goods" :goods-id="goodsId" :hide-stock="sku.hide_stock" @buy-clicked="onBuyClicked" @add-cart="onAddCartClicked" @stepper-change="stepperChange" @sku-selected="skuSelected" reset-stepper-on-hide reset-selected-sku-on-hide>
      <template #sku-header-price="sku">
        <div class="van-sku__goods-price">
          <span class="van-sku__price-symbol">￥</span><span class="van-sku__price-num" v-if="select_price_num.totalPrice !== 0">{{ select_price_num.totalPrice }}</span>
          <span class="van-sku__price-num" v-else>{{ sku.price }}</span>
        </div>
      </template>
    </van-sku>
  </div>
</template>

<script>
export default {
  mounted() {
    this.get_cuisine_list();
    this.get_dish_list();
  },
  data() {
    return {
      activeKey: 0,
      cuisine_list: [],
      dish_list: [],
      // sku
      show: false,
      sku: {
        // 所有sku规格类目与其值的从属关系，比如商品有颜色和尺码两大类规格，颜色下面又有红色和蓝色两个规格值。
        // 可以理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值。
        tree: [
          {
            k: '口味', // skuKeyName：规格类目名称
            k_s: 's1', // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
            v: [
              // {
              //   id: "1", // skuValueId：规格值 id
              //   name: "不辣", // skuValueName：规格值名称
              // },
              // {
              //   id: "2",
              //   name: "麻辣",
              // },
            ],
          },
        ],
        // 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
        list: [
          // {
          //   id: 0, // skuId
          //   s1: "1", // 规格类目 k_s 为 s1 的对应规格值 id
          //   price: 100, // 价格（单位分）
          //   stock_num: 999, // 当前 sku 组合对应的库存
          // },
          // {
          //   id: 1, // skuId
          //   s1: "2", // 规格类目 k_s 为 s1 的对应规格值 id
          //   price: 100, // 价格（单位分）
          //   stock_num: 999, // 当前 sku 组合对应的库存
          // },
        ],
        price: '', // 默认价格（单位元）
        collection_id: 0, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
        none_sku: false, // 是否无规格商品
        stock_num: 999,
        // messages: [
        //   {
        //     // 商品留言
        //     datetime: "0", // 留言类型为 time 时，是否含日期。'1' 表示包含
        //     multiple: "0", // 留言类型为 text 时，是否多行文本。'1' 表示多行
        //     name: "备注", // 留言名称
        //     type: "text", // 留言类型，可选: id_no（身份证）, text, tel, date, time, email
        //     required: "0", // 是否必填 '1' 表示必填
        //     placeholder: "请填写你的要求", // 可选值，占位文本
        //     extraDesc: "", // 可选值，附加描述文案
        //   },
        // ],
        hide_stock: true, // 是否隐藏剩余库存
      },
      goods: {
        picture: '',
      },
      goodsId: '',
      select_price_num: {
        price: 0,
        num: 1,
        totalPrice: 0,
      },
      keyword: '', //搜索关键字
    };
  },
  watch: {
    show(newVal) {
      if (!newVal) {
        this.select_price_num.totalPrice = 0;
      }
    },
  },
  methods: {
    onSearch(val) {
      this.activeKey = 0;
      this.req.get('/dish', { params: { name: val } }).then((res) => {
        this.dish_list = res.rows;
      });
    },
    onClear() {
      this.activeKey = 0;
      this.keyword = null;
      this.req.get('/dish').then((res) => {
        this.dish_list = res.rows;
      });
    },
    get_cuisine_list() {
      this.req.get('/cuisine').then((res) => {
        this.cuisine_list = res.rows;
      });
    },
    get_dish_list(id) {
      let params = {};
      id ? (params.cuisineId = id) : (params = {});
      this.req.get('/dish', { params }).then((res) => {
        this.dish_list = res.rows;
      });
    },
    add_cart(item) {
      this.show = true;
      this.goods.picture = 'http://8.138.102.145/images/' + item.img;
      if (item.itemList.length) {
        this.sku.tree[0] = {
          k: '口味',
          k_s: 's1',
          v: item.itemList.map((v) => {
            return { id: v.id, name: v.name };
          }),
        };
        this.sku.list = item.itemList.map((v) => {
          return {
            id: v.id,
            name: v.name,
            s1: v.id,
            price: (item.price + v.price) * 100,
            stock_num: 999,
          };
        });
      } else {
        this.sku.tree[0] = {
          k: '口味',
          k_s: 's1',
          v: [{ id: 0, name: '无' }],
        };
        this.sku.list = [
          {
            id: 0,
            s1: 0,
            price: item.price * 100,
            stock_num: 999,
          },
        ];
      }
      this.sku.price = item.price;
      this.goodsId = item.id;
    },
    onBuyClicked(val) {
      console.log(val);
      let result = {
        dishId: val.goodsId,
        price: val.selectedSkuComb.price / 100,
        quantity: val.selectedNum,
        status: 0,
        tasteId: val.selectedSkuComb.id,
      };
      this.show = false;
      this.$router.push({
        path: '/pay',
        query: {
          list: JSON.stringify(result),
        },
      });
    },
    onAddCartClicked(val) {
      let result = {
        dishId: val.goodsId,
        price: val.selectedSkuComb.price / 100,
        quantity: val.selectedNum,
        status: 0,
        tasteId: val.selectedSkuComb.id,
        type: 0,
      };
      this.req.post('/cart', result);
      this.show = false;
      this.$notify({
        type: 'success',
        message: '加入购物车成功',
      });
    },
    stepperChange(val) {
      this.select_price_num.num = val;
      // this.sku.list.forEach((v) => {
      //   v.price = this.select_price_num.num * this.select_price_num.price * 100;
      // });
      // this.sku.price = this.select_price_num.num * this.select_price_num.price;
      this.select_price_num.totalPrice = this.select_price_num.num * this.select_price_num.price;
      console.log(this.sku.price);
    },
    skuSelected(val) {
      console.log(val);
      if (!val.selectedSkuComb) {
        this.select_price_num.price = 0;
      } else {
        this.select_price_num.price = val.selectedSkuComb.price / 100;
      }
      // this.sku.list.forEach((v) => {
      //   v.price =
      //     (this.select_price_num.num == 0 ? 1 : this.select_price_num.num) *
      //     this.select_price_num.price *
      //     100;
      // });
      // this.sku.price = this.select_price_num.num * this.select_price_num.price;
      this.select_price_num.totalPrice = this.select_price_num.num * this.select_price_num.price;
      console.log(this.sku.price);
    },
    //新品推荐、销量霸榜、用户好评等模块
    get_dish_list_type(type) {
      let params = {};
      type ? (params.type = type) : (params = {});
      this.req.get('/dish', { params }).then((res) => {
        this.dish_list = res.rows;
      });
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  height: calc(100vh - 50px);
  display: flex;

  .aside {
    width: 6.25rem;
    background-color: #f7f8fa;
  }
  main {
    flex: 1;
    padding: 0.625rem;
    background-color: #fff;
    overflow: scroll;
  }
}
</style>
